<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryFormRef"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="公告标题" prop="noticeTitle">
        <el-input v-model="queryParams.title" placeholder="请输入公告标题" clearable />
      </el-form-item>
      <el-form-item label="类型" prop="noticeType">
        <el-select v-model="queryParams.type" placeholder="请选择公告类型" clearable filterable>
          <el-option
            v-for="dict in dict?.type?.s_notice_code"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" size="small" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" size="small" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" v-hasPermi="['sys:notice:btn_add']" @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          :disabled="multiple"
          v-hasPermi="['sys:notice:btn_remove']"
          @click="handleDelete"
          >删除</el-button
        >
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="noticeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="公告标题" prop="title" :show-overflow-tooltip="true" />
      <el-table-column label="公告类型" prop="type" width="100">
        <template #default="scope">
          <dict-tag :options="dict?.type?.s_notice_code" :value="scope.row.type" />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="createTime" width="100">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            v-if="scope.row.type == '0' || scope.row.type == '1' || scope.row.type == '2'"
            type="text"
            v-hasPermi="['sys:notice:btn_update']"
            @click="handleUpdate(scope.row)"
            >修改</el-button
          >

          <el-button
            v-if="scope.row.type == '3' || scope.row.type == '4' || scope.row.type == '5'"
            type="text"
            v-hasPermi="['sys:notice:btn_view']"
            @click="handleUpdate(scope.row)"
            >详情</el-button
          >

          <el-button
            type="text"
            style="color: #383838"
            v-hasPermi="['sys:notice:btn_remove']"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改公告对话框 -->
    <el-dialog
      :title="title"
      v-model="open"
      width="780px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="公告标题" prop="title">
              <el-input v-model="form.title" placeholder="请输入公告标题" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="公告类型" prop="type">
              <el-select v-model="form.type" placeholder="请选择公告类型">
                <el-option
                  v-for="dict in dict?.type?.s_notice_code"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="内容">
              <editor v-model:value="form.content" :min-height="192" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-if="
              form.type == undefined ||
              form.type == null ||
              form.type == '0' ||
              form.type == '1' ||
              form.type == '2'
            "
            type="primary"
            @click="submitForm"
            >确 定</el-button
          >
          <el-button
            v-if="
              form.type == undefined ||
              form.type == null ||
              form.type == '0' ||
              form.type == '1' ||
              form.type == '2'
            "
            @click="cancel"
            >取 消</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElForm, ElMessage, ElMessageBox } from 'element-plus'
import { listNotice, getNotice, delNotice, addNotice, updateNotice } from '@/api/notice/notice'
import { parseTime } from '@/utils/cj'
import DictTag from '@/components/DictTag/index.vue'
import Editor from '@/components/Editor/index.vue'
import Pagination from '@/components/Pagination/index.vue'
import RightToolbar from '@/components/RightToolbar/index.vue'

// 定义组件名称
defineOptions({
  name: 'Notice',
})

// 定义字典类型
interface DictItem {
  value: string
  label: string
  raw: any
}

interface Dict {
  type: {
    s_notice_code: DictItem[]
  }
}

// 定义公告数据类型
interface NoticeItem {
  id?: number | string
  title?: string
  type?: string
  content?: string
  createTime?: string
  [key: string]: any
}

// 定义表单类型
interface Form {
  id?: number | string
  title?: string
  type?: string
  content?: string
  status?: string
  [key: string]: any
}

// 定义查询参数类型
interface QueryParams {
  pageNum: number
  pageSize: number
  title?: string
  type?: string
  [key: string]: any
}

// 定义校验规则类型
interface Rules {
  title: any[]
  type: any[]
  [key: string]: any[]
}

// Refs
const queryFormRef = ref<InstanceType<typeof ElForm>>()
const formRef = ref<InstanceType<typeof ElForm>>()
const loading = ref(true)
const ids = ref<Array<number | string>>([])
const single = ref(true)
const multiple = ref(true)
const showSearch = ref(true)
const total = ref(0)
const noticeList = ref<NoticeItem[]>([])
const title = ref('')
const open = ref(false)

// 数据定义
const dict = reactive<Dict>({
  type: {
    s_notice_code: [],
  },
}) as Dict

const queryParams = reactive<QueryParams>({
  pageNum: 1,
  pageSize: 10,
  title: undefined,
  type: undefined,
})

const form = reactive<Form>({
  id: undefined,
  title: undefined,
  type: undefined,
  content: undefined,
  status: '0',
})

const rules = reactive<Rules>({
  title: [{ required: true, message: '公告标题不能为空', trigger: 'blur' }],
  type: [{ required: true, message: '公告类型不能为空', trigger: 'change' }],
})

// 挂载时执行
onMounted(() => {
  getList()
})

// 获取字典数据
defineExpose({
  dicts: ['s_notice_code'],
})

/** 查询公告列表 */
const getList = () => {
  loading.value = true
  listNotice(queryParams).then((response: any) => {
    noticeList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
const cancel = () => {
  open.value = false
  reset()
}

// 表单重置
const reset = () => {
  Object.assign(form, {
    id: undefined,
    title: undefined,
    type: undefined,
    content: undefined,
    status: '0',
  })
  formRef.value?.resetFields()
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

// 多选框选中数据
const handleSelectionChange = (selection: NoticeItem[]) => {
  ids.value = selection.map((item) => item.id as number | string)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset()
  open.value = true
  title.value = '添加公告'
}

/** 修改按钮操作 */
const handleUpdate = (row: NoticeItem) => {
  reset()
  const noticeId = row.id || ids.value
  getNotice(noticeId).then((response: any) => {
    Object.assign(form, response.data)
    open.value = true
    title.value = '修改公告'
  })
}

/** 提交按钮 */
const submitForm = () => {
  if (!formRef.value) return
  formRef.value.validate((valid: boolean) => {
    if (valid) {
      if (form.id !== undefined) {
        updateNotice(form).then((response: any) => {
          ElMessage.success('修改成功')
          open.value = false
          getList()
        })
      } else {
        addNotice(form).then((response: any) => {
          ElMessage.success('新增成功')
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
const handleDelete = (row: NoticeItem) => {
  const noticeIds = row.id || ids.value
  ElMessageBox.confirm('是否确认删除？')
    .then(() => {
      return delNotice(noticeIds)
    })
    .then(() => {
      getList()
      ElMessage.success('删除成功')
    })
    .catch(() => {})
}
</script>

<style scoped></style>
